//
//  BankListTableViewController.m
//  HYApp
//
//  Created by Jianbo Cai on 2020/8/21.
//  Copyright © 2020 Unidax. All rights reserved.
//

#import "BankListTableViewController.h"
#import "BankAccountsTableViewCell.h"
#import "NoDataTableViewCell.h"
#import "AddBankAccountTableViewController.h"
#import "HYNetHelper.h"
#import <MJRefresh.h>
#import "NoDataTableViewCell.h"
#import "AddAddressViewController.h"
#import "CryptoAddressEntity.h"

@interface BankListTableViewController ()

@property (nonatomic, assign) BOOL isEdit;
@property (nonatomic, strong) NSArray *dataSource;

@property (weak, nonatomic) IBOutlet UIButton *addButton;

@end

@implementation BankListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    if (self.type == 0) {
        self.title = JFMainLocalizedString(@"profile.digital-assets-address");;
        [self.addButton setTitle:JFMainLocalizedString(@"myProfile.AddAdress") forState:UIControlStateNormal];
    }else {
        self.title = JFMainLocalizedString(@"profile.bank-accounts");;
        [self.addButton setTitle:JFMainLocalizedString(@"bank.add-bank") forState:UIControlStateNormal];
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:@"BankAccountsTableViewCell" bundle:nil] forCellReuseIdentifier:@"BankAccountsTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"NoDataTableViewCell" bundle:nil] forCellReuseIdentifier:@"NoDataTableViewCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"delete"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(deleteAction)];
    
    WEAKSELF
    self.tableView.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        [weakSelf requestDataSource];
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)requestDataSource {
    WEAKSELF
    if (self.type == 0) {
        [HYNetHelper userCryptoAddress:^(JFResultVo *resultVo) {
            [weakSelf.tableView.mj_header endRefreshing];
            if (resultVo.errorNo == 0) {
                weakSelf.dataSource = [NSArray yy_modelArrayWithClass:[CryptoAddressEntity class] json:resultVo.results[@"data"]];
                [weakSelf.tableView reloadData];
            }
        }];
    }else{
        [HYNetHelper bankAccount:^(JFResultVo *resultVo) {
            [weakSelf.tableView.mj_header endRefreshing];
            if (resultVo.errorNo == 0) {
                NSArray *array = [NSArray yy_modelArrayWithClass:[BankAccountListEntity class] json:resultVo.results[@"data"]];
                NSMutableArray *array1 = [NSMutableArray arrayWithCapacity:5];
                for (BankAccountListEntity *bank in array) {
                    if (!bank.disabled) {
                        if (weakSelf.bankCountry) {// 如果传了银行地区，必须银行地区与地区一致才添加
                            if ([bank.datas.country isEqualToString:self.bankCountry]) {
                                [array1 addObject:bank];
                            }
                        }else {
                            [array1 addObject:bank];
                        }
                    }
                }
                weakSelf.dataSource = [NSArray arrayWithArray:array1];
                [weakSelf.tableView reloadData];
            }
        }];
    }
}

- (void)requestDeleteBank {
    [SLRemindView showHUDAddedTo:self.view animated:YES];
    
     dispatch_group_t downloadGroup = dispatch_group_create();
    
    WEAKSELF
    if (self.type == 0) {
        for (CryptoAddressEntity *entity in self.dataSource) {
            if (entity.select) {
                dispatch_group_enter(downloadGroup);
                [HYNetHelper userCryptoAddressDeleteWithId:entity.ID callback:^(JFResultVo *resultVo) {
                    dispatch_group_leave(downloadGroup);
                    
                    if (!resultVo.errorNo) {
                        
                    }
                }];
            }
        }
    }else {
        for (BankAccountListEntity *entity in self.dataSource) {
            if (entity.select) {
                dispatch_group_enter(downloadGroup);
                [HYNetHelper bankAccountDeleteWithId:entity.ID callback:^(JFResultVo *resultVo) {
                    dispatch_group_leave(downloadGroup);
                    
                    if (!resultVo.errorNo) {
                    }
                }];
            }
        }
    }
    
    dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [SLRemindView hideHUDForView:self.view animated:YES];
            [weakSelf updateEdit:NO];
            [weakSelf.tableView.mj_header beginRefreshing];
        });
    });
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self.tableView.mj_header beginRefreshing];
}

- (IBAction)addBankAction:(id)sender {
    if (self.type == 0) {
        AddAddressViewController *vc = [[UIStoryboard storyboardWithName:@"User" bundle:nil]instantiateViewControllerWithIdentifier:@"AddAddressViewController"];;
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        AddBankAccountTableViewController *vc = [[UIStoryboard storyboardWithName:@"User" bundle:nil]instantiateViewControllerWithIdentifier:@"AddBankAccountTableViewController"];;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)deleteAction {
    [self updateEdit:!self.isEdit];

}

- (void)updateEdit:(BOOL)edit {
    self.isEdit = edit;
    if (edit) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"shut_down_iocn"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(cancleDeleteAction)];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"delete"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(submitDeleteAction)];
    }else {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"return"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(goback)];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"delete"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(deleteAction)];
    }
    [self.tableView reloadData];
}

- (void)cancleDeleteAction {
    [self updateEdit:NO];
}

- (void)submitDeleteAction {
    BOOL haveDeleteData = NO;
    if (self.type == 0) {
        for (CryptoAddressEntity *entity in self.dataSource) {
            if (entity.select) {
                haveDeleteData = YES;
                break;
            }
        }
    }else {
        for (BankAccountListEntity *entity in self.dataSource) {
            if (entity.select) {
                haveDeleteData = YES;
                break;
            }
        }
    }
    
    
    WEAKSELF
    if (haveDeleteData) {
        NSString *string = self.type ? JFMainLocalizedString(@"delete_account_tips") : JFMainLocalizedString(@"delete_address_tips");
        FZAlertController *alertController = [FZAlertController alertControllerWithTitleImage:[UIImage imageNamed:@"prompt_icon"] title:string customView:nil message:nil];
        alertController.showCloseBtn = YES;
        alertController.messageAlignment = NSTextAlignmentCenter;
        
        FZAlertAction *action = [FZAlertAction actionWithTitle:JFMainLocalizedString(@"bank.delete") style:UIAlertActionStyleDefault handler:^(FZAlertAction *action) {
            [weakSelf requestDeleteBank];
                            }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
    }else {
        FZAlertController *alertController = [FZAlertController alertControllerWithTitleImage:[UIImage imageNamed:@"prompt_icon"] title:JFMainLocalizedString(@"delete.select") customView:nil message:nil];
        alertController.showCloseBtn = YES;
        alertController.messageAlignment = NSTextAlignmentCenter;
        
        FZAlertAction *action = [FZAlertAction actionWithTitle:JFMainLocalizedString(@"exchange.ok") style:UIAlertActionStyleDefault handler:^(FZAlertAction *action) {
                            }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (void)goback {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return MAX(self.dataSource.count, 1);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.dataSource.count) {
        BankAccountsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BankAccountsTableViewCell" forIndexPath:indexPath];
        cell.edit = self.isEdit;
        if (self.type == 0) {
            cell.cryptoAddress = self.dataSource[indexPath.row];
            cell.detailBtn.AWtitle(nil, UIControlStateNormal);
            cell.detailBtn.AWimage([UIImage imageNamed:@"edit"], UIControlStateNormal);
        }else {
            cell.bankAccount = self.dataSource[indexPath.row];
            cell.detailBtn.AWtitle(JFMainLocalizedString(@"myProfile.Detail"), UIControlStateNormal);
        }
        return cell;
    }else {
        NoDataTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoDataTableViewCell" forIndexPath:indexPath];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return (self.dataSource.count) ? 60 : 240;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.type == 0) {
        if (self.selectAddress) {
            self.selectAddress(self.dataSource[indexPath.row]);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else {
        if (self.selectBank) {
            self.selectBank(self.dataSource[indexPath.row]);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

@end
